﻿using System.IdentityModel.Tokens.Jwt;
using System.Text.Json;

namespace KeyCloakDemo
{
    internal class Program
    {
        static async Task Main(string[] args)
        {

            using var httpClient = new HttpClient();

            // 请求参数（对应图中的Params设置）
            var parameters = new Dictionary<string, string>
            {
                { "grant_type", "password" },
                { "client_id", "gui" },
                { "username", "aibu" },
                { "password", "g1j2b3456" }
            };

            try
            {
                // 发送POST请求（注意URL中的空格需要修正）
                var response = await httpClient.PostAsync(
                    "http://localhost:8080/realms/aibu/protocol/openid-connect/token",
                    new FormUrlEncodedContent(parameters)
                );

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"Access Token: {responseContent}");


                    // 解析access_token
                    var jsonDoc = JsonDocument.Parse(responseContent);
                    var accessToken = jsonDoc.RootElement.GetProperty("access_token").GetString();

                    // 解码JWT
                    var handler = new JwtSecurityTokenHandler();
                    var jwtToken = handler.ReadJwtToken(accessToken);


                    Console.WriteLine($"用户唯一ID(sub): {jwtToken.Payload.Sub}");
                    Console.WriteLine($"用户唯一ID(sub): {jwtToken.Payload["name"]}");
                }
                else
                {
                    Console.WriteLine($"请求失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"异常: {ex.Message}");
            }

            Console.ReadKey();
        }
    }
}
